<ui:component xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:rich="http://richfaces.org/rich"
	xmlns:s="http://jboss.com/products/seam/taglib"
	xmlns:m="http://www.ol4jsf.org"
	xmlns:o="http://openfaces.org/"
	xmlns:a4j="http://richfaces.org/a4j">

	<style>
		.noMaskClass .rich-mpnl-mask-div {
			display:none;
		}
		.contentRights {
			width:100%;
			height:155px;
			overflow:auto;
		}
	</style>
	
	<a4j:loadScript src="/workflow/transaction/toolbox/js/split.js" />
	
	<script type="text/javascript">
		var pickPointControl;
		var pickSinglePointControl;

		function setOffsetControls(geom, ipLat, ipLon, dir, dist) {
			var p1 = geom.components[0];
			var p2 = geom.components[1]; 

			safeSetValue(ipLat, p1.y);
			safeSetValue(ipLon, p1.x);
			safeSetValue(dir, cardinalDirection(p1, p2));
			safeSetValue(dist, geom.getLength());
		}

		function safeSetValue(obj, valueToSet) {
			if (obj != undefined)
				if (obj != null)
					obj.value = valueToSet;
		}
		
		function getSelectControl() {
			var selectControl = null;
			for (var i = 0; i &lt; mapEditor.controls.length; i++)
				if (mapEditor.controls[i].id == 'parcelSelectControl') {
					selectControl = mapEditor.controls[i];
					break;
				}
			return selectControl;
		}
		function getPickPointControl() {
			if (pickPointControl == null) {
				for (var i = 0; i &lt; mapEditor.controls.length; i++)
					if (mapEditor.controls[i].id == 'pickPointControl') {
						pickPointControl = mapEditor.controls[i];
						break;
					}
				if (pickPointControl == null) {
					var control = new OpenLayers.Control({});
	
					pickPointControl = new OpenLayers.Control.DrawFeature(
							polyLayer, OpenLayers.Handler.Path, {handlerOptions: {maxVertices: 2}});
					pickPointControl.id = 'pickPointControl';
					mapEditor.addControl(pickPointControl);
				}
			}
			
			return pickPointControl;
		}
		function getPickSinglePointControl() {
			if (pickSinglePointControl == null) {
				for (var i = 0; i &lt; mapEditor.controls.length; i++)
					if (mapEditor.controls[i].id == 'pickSinglePointControl') {
						pickSinglePointControl = mapEditor.controls[i];
						break;
					}
				if (pickSinglePointControl == null) {
					var control = new OpenLayers.Control({});
	
					pickSinglePointControl = new OpenLayers.Control.DrawFeature(
							polyLayer, OpenLayers.Handler.Point);
					pickSinglePointControl.id = 'pickSinglePointControl';
					mapEditor.addControl(pickSinglePointControl);
				}
			}

			return pickSinglePointControl;
		}
		
	
		function resetInputs() {
			resetMethod1Inputs();
			resetMethod2Inputs();
			resetMethod3Inputs();
			vlayer.destroyFeatures();
	
			var selectControl = getSelectControl();
			if (selectControl != null)
				getSelectControl().unselectAll();
		}
	
		function clearMap() {
			vlayer.destroyFeatures();
		}
	
		
		function addOffsetFeatures(lineFeature, previousFeatures, removeAll) {
			var layer = lineFeature.layer;

			if (removeAll) {
				var i = 0;
				while (i &lt; layer.features.size()) {
					if (lineFeature != layer.features[i])
						layer.destroyFeatures(layer.features[i]);
					else
						i++;
				}
			}
			else {
				if (previousFeatures != undefined)
					if (previousFeatures != null)
						layer.destroyFeatures(previousFeatures);
			}

			var fps = getLinePointsFeature(lineFeature);

			var featuresToAdd = [lineFeature, fps[0], fps[1]]; 
			layer.addFeatures(featuresToAdd);

			return featuresToAdd;
		}
		
		function setLineLength(lineFeature, distValue) {
			var offsetLayer = lineFeature.layer;
			var newLine = newLineFromPoints(lineFeature.geometry, false, distValue);
			var attributes = {name: "my name", bar: "foo"};

			var newLineFeature = new OpenLayers.Feature.Vector(newLine, attributes);
			var fps = getLinePointsFeature(newLineFeature);

			return [newLineFeature, fps[0], fps[1]]; 
		}

		function setLineBearing(lineFeature, radAngle) {
			var offsetLayer = lineFeature.layer;
			var newLine = newLineFromBearing(lineFeature.geometry, radAngle);
			var attributes = {name: "my name", bar: "foo"};

			var newLineFeature = new OpenLayers.Feature.Vector(newLine, attributes);
			var fps = getLinePointsFeature(newLineFeature);

			return [newLineFeature, fps[0], fps[1]]; 
		}

		function getLinePointsFeature(lineFeature) {
			var fp1 = getPointFeature(lineFeature.geometry.components[0].x,
					lineFeature.geometry.components[0].y); 
			var fp2 = getPointFeature(lineFeature.geometry.components[1].x,
					lineFeature.geometry.components[1].y);

			return [fp1, fp2]; 
		}

		function getPointFeature(x, y) {
			var fp1 = new OpenLayers.Feature.Vector(
					new OpenLayers.Geometry.Point(x, y));

			return fp1;
		}
		
		function drawBoundaryAux(splitBorderWKT) {
			if (splitBorderWKT == '') {
				clearMap();
			}
			else {
				var splitBorderFeature = new OpenLayers.Format.WKT().read(splitBorderWKT);
				clearMap();
				vlayer.addFeatures([splitBorderFeature]);
			}
		}
		function drawBoundaryMode() {
			drawBoundary();
			
			var selectControl = getSelectControl();
			if (selectControl != null)
				selectControl.deactivate();
		}
		function drawBoundary() {
			var splitHelper = Seam.Component.getInstance('dataEntryHelper');
			splitHelper.getSplitBorderWKT(drawBoundaryAux);
		}
	</script>

	<h:panelGroup id="drawBoundaryFunctions">
		<script type="text/javascript">
			function drawBoundaryReRender() {
				var wkt = '#{dataEntryHelper.splitBorderWKT}';
				if (wkt != null) {
					if (wkt == '') {
						clearMap();
					}
					else {
						var splitBorderFeature = new OpenLayers.Format.WKT().read(wkt);
						clearMap();
						vlayer.addFeatures([splitBorderFeature]);
					}
				}
			}
		</script>
	</h:panelGroup>
	
	<rich:modalPanel id="splitPanelToolbox" minWidth="520" minHeight="510" resizeable="true" styleClass="noMaskClass" zindex="10000">
		<f:facet name="header">
			<h:outputText value="Division de parcela"/>
		</f:facet>
		
		<f:facet name="controls">
			<h:panelGroup>
				<h:graphicImage value="/img/close.png" styleClass="hidelink"
					id="hideSplitPanel" />
				<rich:componentControl for="splitPanelToolbox" attachTo="hideSplitPanel"
					operation="hide" event="onclick" />
			</h:panelGroup>
		</f:facet>

		<h:form id="splitParcelPanel">
			<ui:include src="./includes/selectedParcelTlb.xhtml" />
		</h:form>

		<rich:tabPanel switchType="client">
			<rich:tab label="Lista de puntos">
				<ui:include src="includes/splitMethod1.xhtml" />
			</rich:tab>
			
			<rich:tab label="Rumbo y distancia a cada punto iniciando en punto de referencia conocido">
				<ui:include src="includes/splitMethod2.xhtml" />
			</rich:tab>
			
			<rich:tab label="Par de puntos de referencia conocidos con rumbo y distancia">
				<ui:include src="includes/splitMethod3.xhtml" />
			</rich:tab>
		</rich:tabPanel>
		
		<br />
		
		<h:form>
			<div align="center">
				<a4j:commandButton value="Aplicar cambios" action="#{dataEntryHelper.splitHelper.applySplit}"
						reRender="#{dataEntryHelper.reRenderList(true)}, drawParcelFunctions, requestedParcelList, coords, bearingAndDistanceTable"
						oncomplete="if (#{facesContext.maximumSeverity==null}) {drawParcelsReRender(); resetInputs();} else #{rich:component('msgPanel')}.show();">
					<f:setPropertyActionListener target="#{dataEntryHelper.requestedParcels}" value="#{null}" />
					<f:setPropertyActionListener target="#{dataEntryHelper.neighborParcels}" value="#{null}" />
				</a4j:commandButton>
			</div>

			<a4j:jsFunction name="deleteLastBoundaryPoint"
				action="#{dataEntryHelper.splitHelper.deleteLastBoundaryPoint}"
				reRender="coords, bearingAndDistanceTable"
				oncomplete="drawBoundaryMode()">
			</a4j:jsFunction>
			<a4j:jsFunction name="clearBoundary"
				action="#{dataEntryHelper.splitHelper.clearBoundary}"
				reRender="coords, bearingAndDistanceTable"
				oncomplete="resetInputs(); clearMap();">
			</a4j:jsFunction>
			<a4j:jsFunction
				name="uploadFileFun"
				action="#{dataEntryHelper.splitHelper.uploadNewFile}"
				reRender="frmUploadFile"
				oncomplete="#{rich:component('uploadFileDlg')}.show();">
			</a4j:jsFunction>
		</h:form>
	</rich:modalPanel>
	
	
	<rich:modalPanel id="uploadFileDlg" minWidth="340" minHeight="230" zindex="15000">
		<f:facet name="header">
			<h:outputText value="Subir archivo con frontera" />
		</f:facet>
		
		<h:form id="frmUploadFile">
			<a4j:jsFunction name="refreshInfo" reRender="info,buttons">
			</a4j:jsFunction>
			<div style="height:170px;width:100%;overflow:auto;">
				<h:panelGroup id="info">
					<h:panelGrid columns="2" width="100%">
						<h:outputText
							value="#{messages['intro2.file']}:"
							style="font-weight:bold;">
						</h:outputText>
						<h:panelGroup>
							<h:outputText
								id="nombreArchivo"
								value="#{dataEntryHelper.splitHelper.selectedFile.fileName.toUpperCase()}"
								rendered="#{dataEntryHelper.splitHelper.selectedFile != null}">
							</h:outputText>
							<rich:fileUpload rendered="#{dataEntryHelper.splitHelper.selectedFile == null}" acceptedTypes="txt,shp"
									allowFlash="false" autoclear="false" noDuplicate="true"
									maxFilesQuantity="1" immediateUpload="true" clearAllControlLabel="" clearControlLabel=""
									fileUploadListener="#{dataEntryHelper.splitHelper.attachFileListener}"
									listHeight="80" listWidth="250" addControlLabel="Seleccionar"
									ontyperejected="alert('Formato de archivo no soportado. Debe ser ESRI Shapefile (SHP).')"
									onfileuploadcomplete="refreshInfo()">
							</rich:fileUpload>
						</h:panelGroup>
					</h:panelGrid>
					<br />
					<h:panelGroup rendered="#{dataEntryHelper.splitHelper.selectedFile != null}">
						<ul>
							<li>
								<h:outputText value="Haga clic en Aceptar para aplicar los datos de frontera proveniente del archivo" />
							</li>
							<li>
								<h:outputText value="Haga clic en Cancelar para descartar los datos provenientes" />
							</li>
						</ul>
					</h:panelGroup>
				</h:panelGroup>
			</div>
			
			<h:panelGroup id="buttons">
				<div align="center">
					<a4j:commandButton
						value="#{messages['button.ok']}"
						action="#{dataEntryHelper.splitHelper.acceptSelectedFile}"
						oncomplete="if (#{facesContext.maximumSeverity == null}) { resetCoordInputs(); drawBoundaryMode(); #{rich:component('uploadFileDlg')}.hide(); } else #{rich:component('msgPanel')}.show();"
						rendered="#{dataEntryHelper.splitHelper.selectedFile != null}"
						reRender="coords, bearingAndDistanceTable">
					</a4j:commandButton>
					<o:commandButton
						value="#{messages['button.cancel']}"
						type="button"
						onclick="#{rich:component('uploadFileDlg')}.hide()">
					</o:commandButton>
				</div>
			</h:panelGroup>
		</h:form>
	</rich:modalPanel>
</ui:component>

